package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private final static String KEY_PREFIX = "user:verify:code:";

    @Override
    public Boolean existDataType(String data, Integer type) {
        //判断type是否是1或者2
        if (type != 1 && type != 2) {
            //不和规范
            throw new LyException(400, "参数有误");
        }
        //判断type的类型，按条件查询,获取数量
        Integer count = query().eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count();
        //判断数量是否为1
        return count == 1;
    }

    @Override
    public void sendCode(String phone) {
        //判断手机号码是否符合规范
        if (!RegexUtils.isPhone(phone)) {
            //手机号码格式不行
            throw new LyException(400, "参数格式错误！");
        }
        //获取六位数的随机数
        String code = RandomStringUtils.randomNumeric(6);
        //写入redis中,有效期五分钟
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
        //发送短信
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,map);
    }

    @Override
    @Transactional
    public void registry(User user, String code) {
        //1.验证码校验
        //从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        //判断是否相同
        if (!StringUtils.equalsIgnoreCase(code, redisCode)) {
            //不相同
            throw new LyException(400, "验证码不正确！");
        }
        //2。校验用户信息 todo

        //3.用户的密码加密
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        //4.将用户添加到数据库中
        save(user);
    }

    @Override
    public UserDTO queryUser(String username, String password) {
        //根据用户名查询
        User user = query().eq("username", username).one();
        //判断是否有数据
        if (user == null) {
            //没有数据
            throw new LyException(400, "用户名或密码错误！");
        }
        //拿数据库的密码和输入的密码比较
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        //判断密码比较的结果
        if (!matches) {
            //密码不同
            throw new LyException(400, "用户名或密码错误！");
        }
        //转换为Dto并返回
        return new UserDTO(user);
    }
}
